home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perlop.z / perlop
Text File  |  1998-10-30  |  68KB  |  1,717 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlop - Perl operators and precedence
  10.  
  11. SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
  12.      Perl operators have the following associativity and precedence, listed
  13.      from highest precedence to lowest.  Note that all operators borrowed from
  14.      C keep the same precedence relationship with each other, even where C's
  15.      precedence is slightly screwy.  (This makes learning Perl easier for C
  16.      folks.)  With very few exceptions, these all operate on scalar values
  17.      only, not array values.
  18.  
  19.          left        terms and list operators (leftward)
  20.          left        ->
  21.          nonassoc    ++ --
  22.          right       **
  23.          right       ! ~ \ and unary + and -
  24.          left        =~ !~
  25.          left        * / % x
  26.          left        + - .
  27.          left        << >>
  28.          nonassoc    named unary operators
  29.          nonassoc    < > <= >= lt gt le ge
  30.          nonassoc    == != <=> eq ne cmp
  31.          left        &
  32.          left        | ^
  33.          left        &&
  34.          left        ||
  35.          nonassoc    ..  ...
  36.          right       ?:
  37.          right       = += -= *= etc.
  38.          left        , =>
  39.          nonassoc    list operators (rightward)
  40.          right       not
  41.          left        and
  42.          left        or xor
  43.  
  44.      In the following sections, these operators are covered in precedence
  45.      order.
  46.  
  47. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  48.      TTTTeeeerrrrmmmmssss aaaannnndddd LLLLiiiisssstttt OOOOppppeeeerrrraaaattttoooorrrrssss ((((LLLLeeeeffffttttwwwwaaaarrrrdddd))))
  49.  
  50.      A TERM has the highest precedence in Perl.  They includes variables,
  51.      quote and quote-like operators, any expression in parentheses, and any
  52.      function whose arguments are parenthesized.  Actually, there aren't
  53.      really functions in this sense, just list operators and unary operators
  54.      behaving as functions because you put parentheses around the arguments.
  55.      These are all documented in the _p_e_r_l_f_u_n_c manpage.
  56.  
  57.      If any list operator (_p_r_i_n_t(), etc.) or any unary operator (_c_h_d_i_r(),
  58.      etc.)  is followed by a left parenthesis as the next token, the operator
  59.      and arguments within parentheses are taken to be of highest precedence,
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  71.  
  72.  
  73.  
  74.      just like a normal function call.
  75.  
  76.      In the absence of parentheses, the precedence of list operators such as
  77.      print, sort, or chmod is either very high or very low depending on
  78.      whether you are looking at the left side or the right side of the
  79.      operator.  For example, in
  80.  
  81.          @ary = (1, 3, sort 4, 2);
  82.          print @ary;         # prints 1324
  83.  
  84.      the commas on the right of the sort are evaluated before the sort, but
  85.      the commas on the left are evaluated after.  In other words, list
  86.      operators tend to gobble up all the arguments that follow them, and then
  87.      act like a simple TERM with regard to the preceding expression.  Note
  88.      that you have to be careful with parentheses:
  89.  
  90.          # These evaluate exit before doing the print:
  91.          print($foo, exit);  # Obviously not what you want.
  92.          print $foo, exit;   # Nor is this.
  93.  
  94.          # These do the print before evaluating exit:
  95.          (print $foo), exit; # This is what you want.
  96.          print($foo), exit;  # Or this.
  97.          print ($foo), exit; # Or even this.
  98.  
  99.      Also note that
  100.  
  101.          print ($foo & 255) + 1, "\n";
  102.  
  103.      probably doesn't do what you expect at first glance.  See the section on
  104.      _N_a_m_e_d _U_n_a_r_y _O_p_e_r_a_t_o_r_s for more discussion of this.
  105.  
  106.      Also parsed as terms are the do {} and eval {} constructs, as well as
  107.      subroutine and method calls, and the anonymous constructors [] and {}.
  108.  
  109.      See also the section on _Q_u_o_t_e _a_n_d _Q_u_o_t_e-_l_i_k_e _O_p_e_r_a_t_o_r_s toward the end of
  110.      this section, as well as the section on _I/_O _O_p_e_r_a_t_o_r_s.
  111.  
  112.      TTTThhhheeee AAAArrrrrrrroooowwww OOOOppppeeeerrrraaaattttoooorrrr
  113.  
  114.      Just as in C and C++, "->" is an infix dereference operator.  If the
  115.      right side is either a [...] or {...} subscript, then the left side must
  116.      be either a hard or symbolic reference to an array or hash (or a location
  117.      capable of holding a hard reference, if it's an lvalue (assignable)).
  118.      See the _p_e_r_l_r_e_f manpage.
  119.  
  120.      Otherwise, the right side is a method name or a simple scalar variable
  121.      containing the method name, and the left side must either be an object (a
  122.      blessed reference) or a class name (that is, a package name).  See the
  123.      _p_e_r_l_o_b_j manpage.
  124.  
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  137.  
  138.  
  139.  
  140.      AAAAuuuuttttoooo----iiiinnnnccccrrrreeeemmmmeeeennnntttt aaaannnndddd AAAAuuuuttttoooo----ddddeeeeccccrrrreeeemmmmeeeennnntttt
  141.  
  142.      "++" and "--" work as in C.  That is, if placed before a variable, they
  143.      increment or decrement the variable before returning the value, and if
  144.      placed after, increment or decrement the variable after returning the
  145.      value.
  146.  
  147.      The auto-increment operator has a little extra builtin magic to it.  If
  148.      you increment a variable that is numeric, or that has ever been used in a
  149.      numeric context, you get a normal increment.  If, however, the variable
  150.      has been used in only string contexts since it was set, and has a value
  151.      that is not null and matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  152.      increment is done as a string, preserving each character within its
  153.      range, with carry:
  154.  
  155.          print ++($foo = '99');      # prints '100'
  156.          print ++($foo = 'a0');      # prints 'a1'
  157.          print ++($foo = 'Az');      # prints 'Ba'
  158.          print ++($foo = 'zz');      # prints 'aaa'
  159.  
  160.      The auto-decrement operator is not magical.
  161.  
  162.      EEEExxxxppppoooonnnneeeennnnttttiiiiaaaattttiiiioooonnnn
  163.  
  164.      Binary "**" is the exponentiation operator.  Note that it binds even more
  165.      tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
  166.      implemented using C's _p_o_w(3) function, which actually works on doubles
  167.      internally.)
  168.  
  169.      SSSSyyyymmmmbbbboooolllliiiicccc UUUUnnnnaaaarrrryyyy OOOOppppeeeerrrraaaattttoooorrrrssss
  170.  
  171.      Unary "!" performs logical negation, i.e., "not".  See also not for a
  172.      lower precedence version of this.
  173.  
  174.      Unary "-" performs arithmetic negation if the operand is numeric.  If the
  175.      operand is an identifier, a string consisting of a minus sign
  176.      concatenated with the identifier is returned.  Otherwise, if the string
  177.      starts with a plus or minus, a string starting with the opposite sign is
  178.      returned.  One effect of these rules is that -bareword is equivalent to
  179.      "-bareword".
  180.  
  181.      Unary "~" performs bitwise negation, i.e., 1's complement.  (See also the
  182.      section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  183.  
  184.      Unary "+" has no effect whatsoever, even on strings.  It is useful
  185.      syntactically for separating a function name from a parenthesized
  186.      expression that would otherwise be interpreted as the complete list of
  187.      function arguments.  (See examples above under the section on _T_e_r_m_s _a_n_d
  188.      _L_i_s_t _O_p_e_r_a_t_o_r_s (_L_e_f_t_w_a_r_d).)
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  203.  
  204.  
  205.  
  206.      Unary "\" creates a reference to whatever follows it.  See the _p_e_r_l_r_e_f
  207.      manpage.  Do not confuse this behavior with the behavior of backslash
  208.      within a string, although both forms do convey the notion of protecting
  209.      the next thing from interpretation.
  210.  
  211.      BBBBiiiinnnnddddiiiinnnngggg OOOOppppeeeerrrraaaattttoooorrrrssss
  212.  
  213.      Binary "=~" binds a scalar expression to a pattern match.  Certain
  214.      operations search or modify the string $_ by default.  This operator
  215.      makes that kind of operation work on some other string.  The right
  216.      argument is a search pattern, substitution, or translation.  The left
  217.      argument is what is supposed to be searched, substituted, or translated
  218.      instead of the default $_.  The return value indicates the success of the
  219.      operation.  (If the right argument is an expression rather than a search
  220.      pattern, substitution, or translation, it is interpreted as a search
  221.      pattern at run time.  This can be is less efficient than an explicit
  222.      search, because the pattern must be compiled every time the expression is
  223.      evaluated.
  224.  
  225.      Binary "!~" is just like "=~" except the return value is negated in the
  226.      logical sense.
  227.  
  228.      MMMMuuuullllttttiiiipppplllliiiiccccaaaattttiiiivvvveeee OOOOppppeeeerrrraaaattttoooorrrrssss
  229.  
  230.      Binary "*" multiplies two numbers.
  231.  
  232.      Binary "/" divides two numbers.
  233.  
  234.      Binary "%" computes the modulus of two numbers.  Given integer operands
  235.      $a and $b: If $b is positive, then $a % $b is $a minus the largest
  236.      multiple of $b that is not greater than $a.  If $b is negative, then $a %
  237.      $b is $a minus the smallest multiple of $b that is not less than $a (i.e.
  238.      the result will be less than or equal to zero).
  239.  
  240.      Binary "x" is the repetition operator.  In a scalar context, it returns a
  241.      string consisting of the left operand repeated the number of times
  242.      specified by the right operand.  In a list context, if the left operand
  243.      is a list in parentheses, it repeats the list.
  244.  
  245.          print '-' x 80;             # print row of dashes
  246.  
  247.          print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over
  248.  
  249.          @ones = (1) x 80;           # a list of 80 1's
  250.          @ones = (5) x @ones;        # set all elements to 5
  251.  
  252.  
  253.      AAAAddddddddiiiittttiiiivvvveeee OOOOppppeeeerrrraaaattttoooorrrrssss
  254.  
  255.      Binary "+" returns the sum of two numbers.
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  269.  
  270.  
  271.  
  272.      Binary "-" returns the difference of two numbers.
  273.  
  274.      Binary "." concatenates two strings.
  275.  
  276.      SSSShhhhiiiifffftttt OOOOppppeeeerrrraaaattttoooorrrrssss
  277.  
  278.      Binary "<<" returns the value of its left argument shifted left by the
  279.      number of bits specified by the right argument.  Arguments should be
  280.      integers.  (See also the section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  281.  
  282.      Binary ">>" returns the value of its left argument shifted right by the
  283.      number of bits specified by the right argument.  Arguments should be
  284.      integers.  (See also the section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  285.  
  286.      NNNNaaaammmmeeeedddd UUUUnnnnaaaarrrryyyy OOOOppppeeeerrrraaaattttoooorrrrssss
  287.  
  288.      The various named unary operators are treated as functions with one
  289.      argument, with optional parentheses.  These include the filetest
  290.      operators, like -f, -M, etc.  See the _p_e_r_l_f_u_n_c manpage.
  291.  
  292.      If any list operator (_p_r_i_n_t(), etc.) or any unary operator (_c_h_d_i_r(),
  293.      etc.)  is followed by a left parenthesis as the next token, the operator
  294.      and arguments within parentheses are taken to be of highest precedence,
  295.      just like a normal function call.  Examples:
  296.  
  297.          chdir $foo    || die;       # (chdir $foo) || die
  298.          chdir($foo)   || die;       # (chdir $foo) || die
  299.          chdir ($foo)  || die;       # (chdir $foo) || die
  300.          chdir +($foo) || die;       # (chdir $foo) || die
  301.  
  302.      but, because * is higher precedence than ||:
  303.  
  304.          chdir $foo * 20;    # chdir ($foo * 20)
  305.          chdir($foo) * 20;   # (chdir $foo) * 20
  306.          chdir ($foo) * 20;  # (chdir $foo) * 20
  307.          chdir +($foo) * 20; # chdir ($foo * 20)
  308.  
  309.          rand 10 * 20;       # rand (10 * 20)
  310.          rand(10) * 20;      # (rand 10) * 20
  311.          rand (10) * 20;     # (rand 10) * 20
  312.          rand +(10) * 20;    # rand (10 * 20)
  313.  
  314.      See also the section on _T_e_r_m_s _a_n_d _L_i_s_t _O_p_e_r_a_t_o_r_s (_L_e_f_t_w_a_r_d).
  315.  
  316.      RRRReeeellllaaaattttiiiioooonnnnaaaallll OOOOppppeeeerrrraaaattttoooorrrrssss
  317.  
  318.      Binary "<" returns true if the left argument is numerically less than the
  319.      right argument.
  320.  
  321.      Binary ">" returns true if the left argument is numerically greater than
  322.      the right argument.
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  335.  
  336.  
  337.  
  338.      Binary "<=" returns true if the left argument is numerically less than or
  339.      equal to the right argument.
  340.  
  341.      Binary ">=" returns true if the left argument is numerically greater than
  342.      or equal to the right argument.
  343.  
  344.      Binary "lt" returns true if the left argument is stringwise less than the
  345.      right argument.
  346.  
  347.      Binary "gt" returns true if the left argument is stringwise greater than
  348.      the right argument.
  349.  
  350.      Binary "le" returns true if the left argument is stringwise less than or
  351.      equal to the right argument.
  352.  
  353.      Binary "ge" returns true if the left argument is stringwise greater than
  354.      or equal to the right argument.
  355.  
  356.      EEEEqqqquuuuaaaalllliiiittttyyyy OOOOppppeeeerrrraaaattttoooorrrrssss
  357.  
  358.      Binary "==" returns true if the left argument is numerically equal to the
  359.      right argument.
  360.  
  361.      Binary "!=" returns true if the left argument is numerically not equal to
  362.      the right argument.
  363.  
  364.      Binary "<=>" returns -1, 0, or 1 depending on whether the left argument
  365.      is numerically less than, equal to, or greater than the right argument.
  366.  
  367.      Binary "eq" returns true if the left argument is stringwise equal to the
  368.      right argument.
  369.  
  370.      Binary "ne" returns true if the left argument is stringwise not equal to
  371.      the right argument.
  372.  
  373.      Binary "cmp" returns -1, 0, or 1 depending on whether the left argument
  374.      is stringwise less than, equal to, or greater than the right argument.
  375.  
  376.      "lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
  377.      by the current locale if use locale is in effect.  See the _p_e_r_l_l_o_c_a_l_e
  378.      manpage.
  379.  
  380.      BBBBiiiittttwwwwiiiisssseeee AAAAnnnndddd
  381.  
  382.      Binary "&" returns its operators ANDed together bit by bit.  (See also
  383.      the section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  384.  
  385.      BBBBiiiittttwwwwiiiisssseeee OOOOrrrr aaaannnndddd EEEExxxxcccclllluuuussssiiiivvvveeee OOOOrrrr
  386.  
  387.      Binary "|" returns its operators ORed together bit by bit.  (See also the
  388.      section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  401.  
  402.  
  403.  
  404.      Binary "^" returns its operators XORed together bit by bit.  (See also
  405.      the section on _I_n_t_e_g_e_r _A_r_i_t_h_m_e_t_i_c.)
  406.  
  407.      CCCC----ssssttttyyyylllleeee LLLLooooggggiiiiccccaaaallll AAAAnnnndddd
  408.  
  409.      Binary "&&" performs a short-circuit logical AND operation.  That is, if
  410.      the left operand is false, the right operand is not even evaluated.
  411.      Scalar or list context propagates down to the right operand if it is
  412.      evaluated.
  413.  
  414.      CCCC----ssssttttyyyylllleeee LLLLooooggggiiiiccccaaaallll OOOOrrrr
  415.  
  416.      Binary "||" performs a short-circuit logical OR operation.  That is, if
  417.      the left operand is true, the right operand is not even evaluated.
  418.      Scalar or list context propagates down to the right operand if it is
  419.      evaluated.
  420.  
  421.      The || and && operators differ from C's in that, rather than returning 0
  422.      or 1, they return the last value evaluated.  Thus, a reasonably portable
  423.      way to find out the home directory (assuming it's not "0") might be:
  424.  
  425.          $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  426.              (getpwuid($<))[7] || die "You're homeless!\n";
  427.  
  428.      As more readable alternatives to && and ||, Perl provides "and" and "or"
  429.      operators (see below).  The short-circuit behavior is identical.  The
  430.      precedence of "and" and "or" is much lower, however, so that you can
  431.      safely use them after a list operator without the need for parentheses:
  432.  
  433.          unlink "alpha", "beta", "gamma"
  434.                  or gripe(), next LINE;
  435.  
  436.      With the C-style operators that would have been written like this:
  437.  
  438.          unlink("alpha", "beta", "gamma")
  439.                  || (gripe(), next LINE);
  440.  
  441.  
  442.      RRRRaaaannnnggggeeee OOOOppppeeeerrrraaaattttoooorrrr
  443.  
  444.      Binary ".." is the range operator, which is really two different
  445.      operators depending on the context.  In a list context, it returns an
  446.      array of values counting (by ones) from the left value to the right
  447.      value.  This is useful for writing for (1..10) loops and for doing slice
  448.      operations on arrays.  Be aware that under the current implementation, a
  449.      temporary array is created, so you'll burn a lot of memory if you write
  450.      something like this:
  451.  
  452.          for (1 .. 1_000_000) {
  453.              # code
  454.          }
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  467.  
  468.  
  469.  
  470.      In a scalar context, ".." returns a boolean value.  The operator is
  471.      bistable, like a flip-flop, and emulates the line-range (comma) operator
  472.      of sssseeeedddd, aaaawwwwkkkk, and various editors.  Each ".." operator maintains its own
  473.      boolean state.  It is false as long as its left operand is false.  Once
  474.      the left operand is true, the range operator stays true until the right
  475.      operand is true, _A_F_T_E_R which the range operator becomes false again.  (It
  476.      doesn't become false till the next time the range operator is evaluated.
  477.      It can test the right operand and become false on the same evaluation it
  478.      became true (as in aaaawwwwkkkk), but it still returns true once.  If you don't
  479.      want it to test the right operand till the next evaluation (as in sssseeeedddd),
  480.      use three dots ("...") instead of two.)  The right operand is not
  481.      evaluated while the operator is in the "false" state, and the left
  482.      operand is not evaluated while the operator is in the "true" state.  The
  483.      precedence is a little lower than || and &&.  The value returned is
  484.      either the null string for false, or a sequence number (beginning with 1)
  485.      for true.  The sequence number is reset for each range encountered.  The
  486.      final sequence number in a range has the string "E0" appended to it,
  487.      which doesn't affect its numeric value, but gives you something to search
  488.      for if you want to exclude the endpoint.  You can exclude the beginning
  489.      point by waiting for the sequence number to be greater than 1.  If either
  490.      operand of scalar ".." is a numeric literal, that operand is implicitly
  491.      compared to the $. variable, the current line number.  Examples:
  492.  
  493.      As a scalar operator:
  494.  
  495.          if (101 .. 200) { print; }  # print 2nd hundred lines
  496.          next line if (1 .. /^$/);   # skip header lines
  497.          s/^/> / if (/^$/ .. eof()); # quote body
  498.  
  499.      As a list operator:
  500.  
  501.          for (101 .. 200) { print; } # print $_ 100 times
  502.          @foo = @foo[0 .. $#foo];    # an expensive no-op
  503.          @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items
  504.  
  505.      The range operator (in a list context) makes use of the magical auto-
  506.      increment algorithm if the operands are strings.  You can say
  507.  
  508.          @alphabet = ('A' .. 'Z');
  509.  
  510.      to get all the letters of the alphabet, or
  511.  
  512.          $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  513.  
  514.      to get a hexadecimal digit, or
  515.  
  516.          @z2 = ('01' .. '31');  print $z2[$mday];
  517.  
  518.      to get dates with leading zeros.  If the final value specified is not in
  519.      the sequence that the magical increment would produce, the sequence goes
  520.      until the next value would be longer than the final value specified.
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  533.  
  534.  
  535.  
  536.      CCCCoooonnnnddddiiiittttiiiioooonnnnaaaallll OOOOppppeeeerrrraaaattttoooorrrr
  537.  
  538.      Ternary "?:" is the conditional operator, just as in C.  It works much
  539.      like an if-then-else.  If the argument before the ? is true, the argument
  540.      before the : is returned, otherwise the argument after the :  is
  541.      returned.  For example:
  542.  
  543.          printf "I have %d dog%s.\n", $n,
  544.                  ($n == 1) ? '' : "s";
  545.  
  546.      Scalar or list context propagates downward into the 2nd or 3rd argument,
  547.      whichever is selected.
  548.  
  549.          $a = $ok ? $b : $c;  # get a scalar
  550.          @a = $ok ? @b : @c;  # get an array
  551.          $a = $ok ? @b : @c;  # oops, that's just a count!
  552.  
  553.      The operator may be assigned to if both the 2nd and 3rd arguments are
  554.      legal lvalues (meaning that you can assign to them):
  555.  
  556.          ($a_or_b ? $a : $b) = $c;
  557.  
  558.      This is not necessarily guaranteed to contribute to the readability of
  559.      your program.
  560.  
  561.      AAAAssssssssiiiiggggnnnnmmmmeeeennnntttt OOOOppppeeeerrrraaaattttoooorrrrssss
  562.  
  563.      "=" is the ordinary assignment operator.
  564.  
  565.      Assignment operators work as in C.  That is,
  566.  
  567.          $a += 2;
  568.  
  569.      is equivalent to
  570.  
  571.          $a = $a + 2;
  572.  
  573.      although without duplicating any side effects that dereferencing the
  574.      lvalue might trigger, such as from _t_i_e().  Other assignment operators
  575.      work similarly.  The following are recognized:
  576.  
  577.          **=    +=    *=    &=    <<=    &&=
  578.                 -=    /=    |=    >>=    ||=
  579.                 .=    %=    ^=
  580.                       x=
  581.  
  582.      Note that while these are grouped by family, they all have the precedence
  583.      of assignment.
  584.  
  585.      Unlike in C, the assignment operator produces a valid lvalue.  Modifying
  586.      an assignment is equivalent to doing the assignment and then modifying
  587.      the variable that was assigned to.  This is useful for modifying a copy
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  599.  
  600.  
  601.  
  602.      of something, like this:
  603.  
  604.          ($tmp = $global) =~ tr [A-Z] [a-z];
  605.  
  606.      Likewise,
  607.  
  608.          ($a += 2) *= 3;
  609.  
  610.      is equivalent to
  611.  
  612.          $a += 2;
  613.          $a *= 3;
  614.  
  615.  
  616.      CCCCoooommmmmmmmaaaa OOOOppppeeeerrrraaaattttoooorrrr
  617.  
  618.      Binary "," is the comma operator.  In a scalar context it evaluates its
  619.      left argument, throws that value away, then evaluates its right argument
  620.      and returns that value.  This is just like C's comma operator.
  621.  
  622.      In a list context, it's just the list argument separator, and inserts
  623.      both its arguments into the list.
  624.  
  625.      The => digraph is mostly just a synonym for the comma operator.  It's
  626.      useful for documenting arguments that come in pairs.  As of release
  627.      5.001, it also forces any word to the left of it to be interpreted as a
  628.      string.
  629.  
  630.      LLLLiiiisssstttt OOOOppppeeeerrrraaaattttoooorrrrssss ((((RRRRiiiigggghhhhttttwwwwaaaarrrrdddd))))
  631.  
  632.      On the right side of a list operator, it has very low precedence, such
  633.      that it controls all comma-separated expressions found there.  The only
  634.      operators with lower precedence are the logical operators "and", "or",
  635.      and "not", which may be used to evaluate calls to list operators without
  636.      the need for extra parentheses:
  637.  
  638.          open HANDLE, "filename"
  639.              or die "Can't open: $!\n";
  640.  
  641.      See also discussion of list operators in the section on _T_e_r_m_s _a_n_d _L_i_s_t
  642.      _O_p_e_r_a_t_o_r_s (_L_e_f_t_w_a_r_d).
  643.  
  644.      LLLLooooggggiiiiccccaaaallll NNNNooootttt
  645.  
  646.      Unary "not" returns the logical negation of the expression to its right.
  647.      It's the equivalent of "!" except for the very low precedence.
  648.  
  649.      LLLLooooggggiiiiccccaaaallll AAAAnnnndddd
  650.  
  651.      Binary "and" returns the logical conjunction of the two surrounding
  652.      expressions.  It's equivalent to && except for the very low precedence.
  653.      This means that it short-circuits: i.e., the right expression is
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  665.  
  666.  
  667.  
  668.      evaluated only if the left expression is true.
  669.  
  670.      LLLLooooggggiiiiccccaaaallll oooorrrr aaaannnndddd EEEExxxxcccclllluuuussssiiiivvvveeee OOOOrrrr
  671.  
  672.      Binary "or" returns the logical disjunction of the two surrounding
  673.      expressions.  It's equivalent to || except for the very low precedence.
  674.      This means that it short-circuits: i.e., the right expression is
  675.      evaluated only if the left expression is false.
  676.  
  677.      Binary "xor" returns the exclusive-OR of the two surrounding expressions.
  678.      It cannot short circuit, of course.
  679.  
  680.      CCCC OOOOppppeeeerrrraaaattttoooorrrrssss MMMMiiiissssssssiiiinnnngggg FFFFrrrroooommmm PPPPeeeerrrrllll
  681.  
  682.      Here is what C has that Perl doesn't:
  683.  
  684.      unary & Address-of operator.  (But see the "\" operator for taking a
  685.              reference.)
  686.  
  687.      unary * Dereference-address operator. (Perl's prefix dereferencing
  688.              operators are typed: $, @, %, and &.)
  689.  
  690.      (TYPE)  Type casting operator.
  691.  
  692.      QQQQuuuuooootttteeee aaaannnndddd QQQQuuuuooootttteeee----lllliiiikkkkeeee OOOOppppeeeerrrraaaattttoooorrrrssss
  693.  
  694.      While we usually think of quotes as literal values, in Perl they function
  695.      as operators, providing various kinds of interpolating and pattern
  696.      matching capabilities.  Perl provides customary quote characters for
  697.      these behaviors, but also provides a way for you to choose your quote
  698.      character for any of them.  In the following table, a {} represents any
  699.      pair of delimiters you choose.  Non-bracketing delimiters use the same
  700.      character fore and aft, but the 4 sorts of brackets (round, angle,
  701.      square, curly) will all nest.
  702.  
  703.          Customary  Generic     Meaning    Interpolates
  704.              ''       q{}       Literal         no
  705.              ""      qq{}       Literal         yes
  706.              ``      qx{}       Command         yes
  707.                      qw{}      Word list        no
  708.              //       m{}    Pattern match      yes
  709.                       s{}{}   Substitution      yes
  710.                      tr{}{}   Translation       no
  711.  
  712.      Note that there can be whitespace between the operator and the quoting
  713.      characters, except when # is being used as the quoting character.  q#foo#
  714.      is parsed as being the string foo, which q #foo# is the operator q
  715.      followed by a comment. Its argument will be taken from the next line.
  716.      This allows you to write:
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  731.  
  732.  
  733.  
  734.          s {foo}  # Replace foo
  735.            {bar}  # with bar.
  736.  
  737.      For constructs that do interpolation, variables beginning with "$" or "@"
  738.      are interpolated, as are the following sequences:
  739.  
  740.          \t          tab             (HT, TAB)
  741.          \n          newline         (LF, NL)
  742.          \r          return          (CR)
  743.          \f          form feed       (FF)
  744.          \b          backspace       (BS)
  745.          \a          alarm (bell)    (BEL)
  746.          \e          escape          (ESC)
  747.          \033        octal char
  748.          \x1b        hex char
  749.          \c[         control char
  750.          \l          lowercase next char
  751.          \u          uppercase next char
  752.          \L          lowercase till \E
  753.          \U          uppercase till \E
  754.          \E          end case modification
  755.          \Q          quote regexp metacharacters till \E
  756.  
  757.      If use locale is in effect, the case map used by \l, \L, \u and <\U> is
  758.      taken from the current locale.  See the _p_e_r_l_l_o_c_a_l_e manpage.
  759.  
  760.      Patterns are subject to an additional level of interpretation as a
  761.      regular expression.  This is done as a second pass, after variables are
  762.      interpolated, so that regular expressions may be incorporated into the
  763.      pattern from the variables.  If this is not what you want, use \Q to
  764.      interpolate a variable literally.
  765.  
  766.      Apart from the above, there are no multiple levels of interpolation.  In
  767.      particular, contrary to the expectations of shell programmers, back-
  768.      quotes do _N_O_T interpolate within double quotes, nor do single quotes
  769.      impede evaluation of variables when used within double quotes.
  770.  
  771.      RRRReeeeggggeeeexxxxpppp QQQQuuuuooootttteeee----LLLLiiiikkkkeeee OOOOppppeeeerrrraaaattttoooorrrrssss
  772.  
  773.      Here are the quote-like operators that apply to pattern matching and
  774.      related activities.
  775.  
  776.      ?PATTERN?
  777.              This is just like the /pattern/ search, except that it matches
  778.              only once between calls to the _r_e_s_e_t() operator.  This is a
  779.              useful optimization when you want to see only the first
  780.              occurrence of something in each file of a set of files, for
  781.              instance.  Only ??  patterns local to the current package are
  782.              reset.
  783.  
  784.              This usage is vaguely deprecated, and may be removed in some
  785.              future version of Perl.
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  797.  
  798.  
  799.  
  800.      m/PATTERN/cgimosx
  801.  
  802.      /PATTERN/cgimosx
  803.              Searches a string for a pattern match, and in a scalar context
  804.              returns true (1) or false ('').  If no string is specified via
  805.              the =~ or !~ operator, the $_ string is searched.  (The string
  806.              specified with =~ need not be an lvalue--it may be the result of
  807.              an expression evaluation, but remember the =~ binds rather
  808.              tightly.)  See also the _p_e_r_l_r_e manpage.  See the _p_e_r_l_l_o_c_a_l_e
  809.              manpage for discussion of additional considerations which apply
  810.              when use locale is in effect.
  811.  
  812.              Options are:
  813.  
  814.                  c   Do not reset search position on a failed match when /g is in effect.
  815.                  g   Match globally, i.e., find all occurrences.
  816.                  i   Do case-insensitive pattern matching.
  817.                  m   Treat string as multiple lines.
  818.                  o   Compile pattern only once.
  819.                  s   Treat string as single line.
  820.                  x   Use extended regular expressions.
  821.  
  822.              If "/" is the delimiter then the initial m is optional.  With the
  823.              m you can use any pair of non-alphanumeric, non-whitespace
  824.              characters as delimiters.  This is particularly useful for
  825.              matching Unix path names that contain "/", to avoid LTS (leaning
  826.              toothpick syndrome).  If "?" is the delimiter, then the match-
  827.              only-once rule of ?PATTERN? applies.
  828.  
  829.              PATTERN may contain variables, which will be interpolated (and
  830.              the pattern recompiled) every time the pattern search is
  831.              evaluated.  (Note that $) and $| might not be interpolated
  832.              because they look like end-of-string tests.)  If you want such a
  833.              pattern to be compiled only once, add a /o after the trailing
  834.              delimiter.  This avoids expensive run-time recompilations, and is
  835.              useful when the value you are interpolating won't change over the
  836.              life of the script.  However, mentioning /o constitutes a promise
  837.              that you won't change the variables in the pattern.  If you
  838.              change them, Perl won't even notice.
  839.  
  840.              If the PATTERN evaluates to a null string, the last successfully
  841.              executed regular expression is used instead.
  842.  
  843.              If used in a context that requires a list value, a pattern match
  844.              returns a list consisting of the subexpressions matched by the
  845.              parentheses in the pattern, i.e., ($1, $2, $3...).  (Note that
  846.              here $1 etc. are also set, and that this differs from Perl 4's
  847.              behavior.)  If the match fails, a null array is returned.  If the
  848.              match succeeds, but there were no parentheses, a list value of
  849.              (1) is returned.
  850.  
  851.              Examples:
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  863.  
  864.  
  865.  
  866.                  open(TTY, '/dev/tty');
  867.                  <TTY> =~ /^y/i && foo();    # do foo if desired
  868.  
  869.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  870.  
  871.                  next if m#^/usr/spool/uucp#;
  872.  
  873.                  # poor man's grep
  874.                  $arg = shift;
  875.                  while (<>) {
  876.                      print if /$arg/o;       # compile only once
  877.                  }
  878.  
  879.                  if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  880.  
  881.              This last example splits $foo into the first two words and the
  882.              remainder of the line, and assigns those three fields to $F1,
  883.              $F2, and $Etc.  The conditional is true if any variables were
  884.              assigned, i.e., if the pattern matched.
  885.  
  886.              The /g modifier specifies global pattern matching--that is,
  887.              matching as many times as possible within the string.  How it
  888.              behaves depends on the context.  In a list context, it returns a
  889.              list of all the substrings matched by all the parentheses in the
  890.              regular expression.  If there are no parentheses, it returns a
  891.              list of all the matched strings, as if there were parentheses
  892.              around the whole pattern.
  893.  
  894.              In a scalar context, m//g iterates through the string, returning
  895.              TRUE each time it matches, and FALSE when it eventually runs out
  896.              of matches.  (In other words, it remembers where it left off last
  897.              time and restarts the search at that point.  You can actually
  898.              find the current match position of a string or set it using the
  899.              _p_o_s() function; see the pos entry in the _p_e_r_l_f_u_n_c manpage.)  A
  900.              failed match normally resets the search position to the beginning
  901.              of the string, but you can avoid that by adding the /c modifier
  902.              (e.g. m//gc).  Modifying the target string also resets the search
  903.              position.
  904.  
  905.              You can intermix m//g matches with m/\G.../g, where \G is a
  906.              zero-width assertion that matches the exact position where the
  907.              previous m//g, if any, left off.  The \G assertion is not
  908.              supported without the /g modifier; currently, without /g, \G
  909.              behaves just like \A, but that's accidental and may change in the
  910.              future.
  911.  
  912.              Examples:
  913.  
  914.                  # list context
  915.                  ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  929.  
  930.  
  931.  
  932.                  # scalar context
  933.                  $/ = ""; $* = 1;  # $* deprecated in modern perls
  934.                  while (defined($paragraph = <>)) {
  935.                      while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  936.                          $sentences++;
  937.                      }
  938.                  }
  939.                  print "$sentences\n";
  940.  
  941.                  # using m//gc with \G
  942.                  $_ = "ppooqppqq";
  943.                  while ($i++ < 2) {
  944.                      print "1: '";
  945.                      print $1 while /(o)/gc; print "', pos=", pos, "\n";
  946.                      print "2: '";
  947.                      print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
  948.                      print "3: '";
  949.                      print $1 while /(p)/gc; print "', pos=", pos, "\n";
  950.                  }
  951.  
  952.              The last example should print:
  953.  
  954.                  1: 'oo', pos=4
  955.                  2: 'q', pos=5
  956.                  3: 'pp', pos=7
  957.                  1: '', pos=7
  958.                  2: 'q', pos=8
  959.                  3: '', pos=8
  960.  
  961.              A useful idiom for lex-like scanners is /\G.../gc.  You can
  962.              combine several regexps like this to process a string part-by-
  963.              part, doing different actions depending on which regexp matched.
  964.              Each regexp tries to match where the previous one leaves off.
  965.  
  966.               $_ = <<'EOL';
  967.                    $url = new URI::URL "http://www/";   die if $url eq "xXx";
  968.               EOL
  969.               LOOP:
  970.                  {
  971.                    print(" digits"),         redo LOOP if /\G\d+\b[,.;]?\s*/gc;
  972.                    print(" lowercase"),      redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
  973.                    print(" UPPERCASE"),      redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
  974.                    print(" Capitalized"),    redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
  975.                    print(" MiXeD"),          redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
  976.                    print(" alphanumeric"),   redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
  977.                    print(" line-noise"),     redo LOOP if /\G[^A-Za-z0-9]+/gc;
  978.                    print ". That's all!\n";
  979.                  }
  980.  
  981.              Here is the output (split into several lines):
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  995.  
  996.  
  997.  
  998.               line-noise lowercase line-noise lowercase UPPERCASE line-noise
  999.               UPPERCASE line-noise lowercase line-noise lowercase line-noise
  1000.               lowercase lowercase line-noise lowercase lowercase line-noise
  1001.               MiXeD line-noise. That's all!
  1002.  
  1003.  
  1004.      q/STRING/
  1005.  
  1006.      'STRING'
  1007.              A single-quoted, literal string. A backslash represents a
  1008.              backslash unless followed by the delimiter or another backslash,
  1009.              in which case the delimiter or backslash is interpolated.
  1010.  
  1011.                  $foo = q!I said, "You said, 'She said it.'"!;
  1012.                  $bar = q('This is it.');
  1013.                  $baz = '\n';                # a two-character string
  1014.  
  1015.  
  1016.      qq/STRING/
  1017.  
  1018.      "STRING"
  1019.              A double-quoted, interpolated string.
  1020.  
  1021.                  $_ .= qq
  1022.                   (*** The previous line contains the naughty word "$1".\n)
  1023.                              if /(tcl|rexx|python)/;      # :-)
  1024.                  $baz = "\n";                # a one-character string
  1025.  
  1026.  
  1027.      qx/STRING/
  1028.  
  1029.      `STRING`
  1030.              A string which is interpolated and then executed as a system
  1031.              command.  The collected standard output of the command is
  1032.              returned.  In scalar context, it comes back as a single
  1033.              (potentially multi-line) string.  In list context, returns a list
  1034.              of lines (however you've defined lines with $/ or
  1035.              $INPUT_RECORD_SEPARATOR).
  1036.  
  1037.                  $today = qx{ date };
  1038.  
  1039.              Note that how the string gets evaluated is entirely subject to
  1040.              the command interpreter on your system.  On most platforms, you
  1041.              will have to protect shell metacharacters if you want them
  1042.              treated literally.  On some platforms (notably DOS-like ones),
  1043.              the shell may not be capable of dealing with multiline commands,
  1044.              so putting newlines in the string may not get you what you want.
  1045.              You may be able to evaluate multiple commands in a single line by
  1046.              separating them with the command separator character, if your
  1047.              shell supports that (e.g. ; on many Unix shells; & on the Windows
  1048.              NT cmd shell).
  1049.  
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1061.  
  1062.  
  1063.  
  1064.              Beware that some command shells may place restrictions on the
  1065.              length of the command line.  You must ensure your strings don't
  1066.              exceed this limit after any necessary interpolations.  See the
  1067.              platform-specific release notes for more details about your
  1068.              particular environment.
  1069.  
  1070.              Also realize that using this operator frequently leads to
  1071.              unportable programs.
  1072.  
  1073.              See the section on _I/_O _O_p_e_r_a_t_o_r_s for more discussion.
  1074.  
  1075.      qw/STRING/
  1076.              Returns a list of the words extracted out of STRING, using
  1077.              embedded whitespace as the word delimiters.  It is exactly
  1078.              equivalent to
  1079.  
  1080.                  split(' ', q/STRING/);
  1081.  
  1082.              Some frequently seen examples:
  1083.  
  1084.                  use POSIX qw( setlocale localeconv )
  1085.                  @EXPORT = qw( foo bar baz );
  1086.  
  1087.              A common mistake is to try to separate the words with comma or to
  1088.              put comments into a multi-line qw-string.  For this reason the -w
  1089.              switch produce warnings if the STRING contains the "," or the "#"
  1090.              character.
  1091.  
  1092.      s/PATTERN/REPLACEMENT/egimosx
  1093.              Searches a string for a pattern, and if found, replaces that
  1094.              pattern with the replacement text and returns the number of
  1095.              substitutions made.  Otherwise it returns false (specifically,
  1096.              the empty string).
  1097.  
  1098.              If no string is specified via the =~ or !~ operator, the $_
  1099.              variable is searched and modified.  (The string specified with =~
  1100.              must be a scalar variable, an array element, a hash element, or
  1101.              an assignment to one of those, i.e., an lvalue.)
  1102.  
  1103.              If the delimiter chosen is single quote, no variable
  1104.              interpolation is done on either the PATTERN or the REPLACEMENT.
  1105.              Otherwise, if the PATTERN contains a $ that looks like a variable
  1106.              rather than an end-of-string test, the variable will be
  1107.              interpolated into the pattern at run-time.  If you want the
  1108.              pattern compiled only once the first time the variable is
  1109.              interpolated, use the /o option.  If the pattern evaluates to a
  1110.              null string, the last successfully executed regular expression is
  1111.              used instead.  See the _p_e_r_l_r_e manpage for further explanation on
  1112.              these.  See the _p_e_r_l_l_o_c_a_l_e manpage for discussion of additional
  1113.              considerations which apply when use locale is in effect.
  1114.  
  1115.              Options are:
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1127.  
  1128.  
  1129.  
  1130.                  e   Evaluate the right side as an expression.
  1131.                  g   Replace globally, i.e., all occurrences.
  1132.                  i   Do case-insensitive pattern matching.
  1133.                  m   Treat string as multiple lines.
  1134.                  o   Compile pattern only once.
  1135.                  s   Treat string as single line.
  1136.                  x   Use extended regular expressions.
  1137.  
  1138.              Any non-alphanumeric, non-whitespace delimiter may replace the
  1139.              slashes.  If single quotes are used, no interpretation is done on
  1140.              the replacement string (the /e modifier overrides this, however).
  1141.              Unlike Perl 4, Perl 5 treats backticks as normal delimiters; the
  1142.              replacement text is not evaluated as a command.  If the PATTERN
  1143.              is delimited by bracketing quotes, the REPLACEMENT has its own
  1144.              pair of quotes, which may or may not be bracketing quotes, e.g.,
  1145.              s(foo)(bar) or s<foo>/bar/.  A /e will cause the replacement
  1146.              portion to be interpreter as a full-fledged Perl expression and
  1147.              _e_v_a_l()ed right then and there.  It is, however, syntax checked at
  1148.              compile-time.
  1149.  
  1150.              Examples:
  1151.  
  1152.                  s/\bgreen\b/mauve/g;                # don't change wintergreen
  1153.  
  1154.                  $path =~ s|/usr/bin|/usr/local/bin|;
  1155.  
  1156.                  s/Login: $foo/Login: $bar/; # run-time pattern
  1157.  
  1158.                  ($foo = $bar) =~ s/this/that/;
  1159.  
  1160.                  $count = ($paragraph =~ s/Mister\b/Mr./g);
  1161.  
  1162.                  $_ = 'abc123xyz';
  1163.                  s/\d+/$&*2/e;               # yields 'abc246xyz'
  1164.                  s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
  1165.                  s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
  1166.  
  1167.                  s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
  1168.                  s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
  1169.                  s/^=(\w+)/&pod($1)/ge;      # use function call
  1170.  
  1171.                  # /e's can even nest;  this will expand
  1172.                  # simple embedded variables in $_
  1173.                  s/(\$\w+)/$1/eeg;
  1174.  
  1175.                  # Delete C comments.
  1176.                  $program =~ s {
  1177.                      /\*     # Match the opening delimiter.
  1178.                      .*?     # Match a minimal number of characters.
  1179.                      \*/     # Match the closing delimiter.
  1180.                  } []gsx;
  1181.  
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1193.  
  1194.  
  1195.  
  1196.                  s/^\s*(.*?)\s*$/$1/;        # trim white space
  1197.  
  1198.                  s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
  1199.  
  1200.              Note the use of $ instead of \ in the last example.  Unlike sssseeeedddd,
  1201.              we use the \<_d_i_g_i_t> form in only the left hand side.  Anywhere
  1202.              else it's $<_d_i_g_i_t>.
  1203.  
  1204.              Occasionally, you can't use just a /g to get all the changes to
  1205.              occur.  Here are two common cases:
  1206.  
  1207.                  # put commas in the right places in an integer
  1208.                  1 while s/(.*\d)(\d\d\d)/$1,$2/g;      # perl4
  1209.                  1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;  # perl5
  1210.  
  1211.                  # expand tabs to 8-column spacing
  1212.                  1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
  1213.  
  1214.  
  1215.      tr/SEARCHLIST/REPLACEMENTLIST/cds
  1216.  
  1217.      y/SEARCHLIST/REPLACEMENTLIST/cds
  1218.              Translates all occurrences of the characters found in the search
  1219.              list with the corresponding character in the replacement list.
  1220.              It returns the number of characters replaced or deleted.  If no
  1221.              string is specified via the =~ or !~ operator, the $_ string is
  1222.              translated.  (The string specified with =~ must be a scalar
  1223.              variable, an array element, a hash element, or an assignment to
  1224.              one of those, i.e., an lvalue.)  For sssseeeedddd devotees, y is provided
  1225.              as a synonym for tr.  If the SEARCHLIST is delimited by
  1226.              bracketing quotes, the REPLACEMENTLIST has its own pair of
  1227.              quotes, which may or may not be bracketing quotes, e.g., tr[A-
  1228.              Z][a-z] or tr(+-*/)/ABCD/.
  1229.  
  1230.              Options:
  1231.  
  1232.                  c   Complement the SEARCHLIST.
  1233.                  d   Delete found but unreplaced characters.
  1234.                  s   Squash duplicate replaced characters.
  1235.  
  1236.              If the /c modifier is specified, the SEARCHLIST character set is
  1237.              complemented.  If the /d modifier is specified, any characters
  1238.              specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
  1239.              (Note that this is slightly more flexible than the behavior of
  1240.              some ttttrrrr programs, which delete anything they find in the
  1241.              SEARCHLIST, period.)  If the /s modifier is specified, sequences
  1242.              of characters that were translated to the same character are
  1243.              squashed down to a single instance of the character.
  1244.  
  1245.              If the /d modifier is used, the REPLACEMENTLIST is always
  1246.              interpreted exactly as specified.  Otherwise, if the
  1247.              REPLACEMENTLIST is shorter than the SEARCHLIST, the final
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1259.  
  1260.  
  1261.  
  1262.              character is replicated till it is long enough.  If the
  1263.              REPLACEMENTLIST is null, the SEARCHLIST is replicated.  This
  1264.              latter is useful for counting characters in a class or for
  1265.              squashing character sequences in a class.
  1266.  
  1267.              Examples:
  1268.  
  1269.                  $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case
  1270.  
  1271.                  $cnt = tr/*/*/;             # count the stars in $_
  1272.  
  1273.                  $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
  1274.  
  1275.                  $cnt = tr/0-9//;            # count the digits in $_
  1276.  
  1277.                  tr/a-zA-Z//s;               # bookkeeper -> bokeper
  1278.  
  1279.                  ($HOST = $host) =~ tr/a-z/A-Z/;
  1280.  
  1281.                  tr/a-zA-Z/ /cs;             # change non-alphas to single space
  1282.  
  1283.                  tr [\200-\377]
  1284.                     [\000-\177];             # delete 8th bit
  1285.  
  1286.              If multiple translations are given for a character, only the
  1287.              first one is used:
  1288.  
  1289.                  tr/AAA/XYZ/
  1290.  
  1291.              will translate any A to X.
  1292.  
  1293.              Note that because the translation table is built at compile time,
  1294.              neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to
  1295.              double quote interpolation.  That means that if you want to use
  1296.              variables, you must use an _e_v_a_l():
  1297.  
  1298.                  eval "tr/$oldlist/$newlist/";
  1299.                  die $@ if $@;
  1300.  
  1301.                  eval "tr/$oldlist/$newlist/, 1" or die $@;
  1302.  
  1303.  
  1304.      IIII////OOOO OOOOppppeeeerrrraaaattttoooorrrrssss
  1305.  
  1306.      There are several I/O operators you should know about.  A string is
  1307.      enclosed by backticks (grave accents) first undergoes variable
  1308.      substitution just like a double quoted string.  It is then interpreted as
  1309.      a command, and the output of that command is the value of the pseudo-
  1310.      literal, like in a shell.  In a scalar context, a single string
  1311.      consisting of all the output is returned.  In a list context, a list of
  1312.      values is returned, one for each line of output.  (You can set $/ to use
  1313.      a different line terminator.)  The command is executed each time the
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1325.  
  1326.  
  1327.  
  1328.      pseudo-literal is evaluated.  The status value of the command is returned
  1329.      in $? (see the _p_e_r_l_v_a_r manpage for the interpretation of $?).  Unlike in
  1330.      ccccsssshhhh, no translation is done on the return data--newlines remain newlines.
  1331.      Unlike in any of the shells, single quotes do not hide variable names in
  1332.      the command from interpretation.  To pass a $ through to the shell you
  1333.      need to hide it with a backslash.  The generalized form of backticks is
  1334.      qx//.  (Because backticks always undergo shell expansion as well, see the
  1335.      _p_e_r_l_s_e_c manpage for security concerns.)
  1336.  
  1337.      Evaluating a filehandle in angle brackets yields the next line from that
  1338.      file (newline, if any, included), or undef at end of file.  Ordinarily
  1339.      you must assign that value to a variable, but there is one situation
  1340.      where an automatic assignment happens.  _I_f _a_n_d _O_N_L_Y _i_f the input symbol
  1341.      is the only thing inside the conditional of a while or for(;;) loop, the
  1342.      value is automatically assigned to the variable $_.  The assigned value
  1343.      is then tested to see if it is defined.  (This may seem like an odd thing
  1344.      to you, but you'll use the construct in almost every Perl script you
  1345.      write.)  Anyway, the following lines are equivalent to each other:
  1346.  
  1347.          while (defined($_ = <STDIN>)) { print; }
  1348.          while (<STDIN>) { print; }
  1349.          for (;<STDIN>;) { print; }
  1350.          print while defined($_ = <STDIN>);
  1351.          print while <STDIN>;
  1352.  
  1353.      The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
  1354.      filehandles stdin, stdout, and stderr will also work except in packages,
  1355.      where they would be interpreted as local identifiers rather than global.)
  1356.      Additional filehandles may be created with the _o_p_e_n() function.  See the
  1357.      open() entry in the _p_e_r_l_f_u_n_c manpage for details on this.
  1358.  
  1359.      If a <FILEHANDLE> is used in a context that is looking for a list, a list
  1360.      consisting of all the input lines is returned, one line per list element.
  1361.      It's easy to make a _L_A_R_G_E data space this way, so use with care.
  1362.  
  1363.      The null filehandle <> is special and can be used to emulate the behavior
  1364.      of sssseeeedddd and aaaawwwwkkkk.  Input from <> comes either from standard input, or from
  1365.      each file listed on the command line.  Here's how it works: the first
  1366.      time <> is evaluated, the @ARGV array is checked, and if it is null,
  1367.      $ARGV[0] is set to "-", which when opened gives you standard input.  The
  1368.      @ARGV array is then processed as a list of filenames.  The loop
  1369.  
  1370.          while (<>) {
  1371.              ...                     # code for each line
  1372.          }
  1373.  
  1374.      is equivalent to the following Perl-like pseudo code:
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.                                                                        PPPPaaaaggggeeee 22221111
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1391.  
  1392.  
  1393.  
  1394.          unshift(@ARGV, '-') unless @ARGV;
  1395.          while ($ARGV = shift) {
  1396.              open(ARGV, $ARGV);
  1397.              while (<ARGV>) {
  1398.                  ...         # code for each line
  1399.              }
  1400.          }
  1401.  
  1402.      except that it isn't so cumbersome to say, and will actually work.  It
  1403.      really does shift array @ARGV and put the current filename into variable
  1404.      $ARGV.  It also uses filehandle _A_R_G_V internally--<> is just a synonym for
  1405.      <ARGV>, which is magical.  (The pseudo code above doesn't work because it
  1406.      treats <ARGV> as non-magical.)
  1407.  
  1408.      You can modify @ARGV before the first <> as long as the array ends up
  1409.      containing the list of filenames you really want.  Line numbers ($.)
  1410.      continue as if the input were one big happy file.  (But see example under
  1411.      _e_o_f() for how to reset line numbers on each file.)
  1412.  
  1413.      If you want to set @ARGV to your own list of files, go right ahead.  If
  1414.      you want to pass switches into your script, you can use one of the
  1415.      Getopts modules or put a loop on the front like this:
  1416.  
  1417.          while ($_ = $ARGV[0], /^-/) {
  1418.              shift;
  1419.              last if /^--$/;
  1420.              if (/^-D(.*)/) { $debug = $1 }
  1421.              if (/^-v/)     { $verbose++  }
  1422.              ...             # other switches
  1423.          }
  1424.          while (<>) {
  1425.              ...             # code for each line
  1426.          }
  1427.  
  1428.      The <> symbol will return FALSE only once.  If you call it again after
  1429.      this it will assume you are processing another @ARGV list, and if you
  1430.      haven't set @ARGV, will input from STDIN.
  1431.  
  1432.      If the string inside the angle brackets is a reference to a scalar
  1433.      variable (e.g., <$foo>), then that variable contains the name of the
  1434.      filehandle to input from, or a reference to the same.  For example:
  1435.  
  1436.          $fh = \*STDIN;
  1437.          $line = <$fh>;
  1438.  
  1439.      If the string inside angle brackets is not a filehandle or a scalar
  1440.      variable containing a filehandle name or reference, then it is
  1441.      interpreted as a filename pattern to be globbed, and either a list of
  1442.      filenames or the next filename in the list is returned, depending on
  1443.      context.  One level of $ interpretation is done first, but you can't say
  1444.      <$foo> because that's an indirect filehandle as explained in the previous
  1445.      paragraph.  (In older versions of Perl, programmers would insert curly
  1446.  
  1447.  
  1448.  
  1449.                                                                        PPPPaaaaggggeeee 22222222
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1457.  
  1458.  
  1459.  
  1460.      brackets to force interpretation as a filename glob: <${foo}>.  These
  1461.      days, it's considered cleaner to call the internal function directly as
  1462.      glob($foo), which is probably the right way to have done it in the first
  1463.      place.)  Example:
  1464.  
  1465.          while (<*.c>) {
  1466.              chmod 0644, $_;
  1467.          }
  1468.  
  1469.      is equivalent to
  1470.  
  1471.          open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  1472.          while (<FOO>) {
  1473.              chop;
  1474.              chmod 0644, $_;
  1475.          }
  1476.  
  1477.      In fact, it's currently implemented that way.  (Which means it will not
  1478.      work on filenames with spaces in them unless you have _c_s_h(1) on your
  1479.      machine.)  Of course, the shortest way to do the above is:
  1480.  
  1481.          chmod 0644, <*.c>;
  1482.  
  1483.      Because globbing invokes a shell, it's often faster to call _r_e_a_d_d_i_r()
  1484.      yourself and do your own _g_r_e_p() on the filenames.  Furthermore, due to
  1485.      its current implementation of using a shell, the _g_l_o_b() routine may get
  1486.      "Arg list too long" errors (unless you've installed _t_c_s_h(1L) as
  1487.      /_b_i_n/_c_s_h).
  1488.  
  1489.      A glob evaluates its (embedded) argument only when it is starting a new
  1490.      list.  All values must be read before it will start over.  In a list
  1491.      context this isn't important, because you automatically get them all
  1492.      anyway.  In a scalar context, however, the operator returns the next
  1493.      value each time it is called, or a FALSE value if you've just run out.
  1494.      Again, FALSE is returned only once.  So if you're expecting a single
  1495.      value from a glob, it is much better to say
  1496.  
  1497.          ($file) = <blurch*>;
  1498.  
  1499.      than
  1500.  
  1501.          $file = <blurch*>;
  1502.  
  1503.      because the latter will alternate between returning a filename and
  1504.      returning FALSE.
  1505.  
  1506.      It you're trying to do variable interpolation, it's definitely better to
  1507.      use the _g_l_o_b() function, because the older notation can cause people to
  1508.      become confused with the indirect filehandle notation.
  1509.  
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.                                                                        PPPPaaaaggggeeee 22223333
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1523.  
  1524.  
  1525.  
  1526.          @files = glob("$dir/*.[ch]");
  1527.          @files = glob($files[$i]);
  1528.  
  1529.  
  1530.      CCCCoooonnnnssssttttaaaannnntttt FFFFoooollllddddiiiinnnngggg
  1531.  
  1532.      Like C, Perl does a certain amount of expression evaluation at compile
  1533.      time, whenever it determines that all of the arguments to an operator are
  1534.      static and have no side effects.  In particular, string concatenation
  1535.      happens at compile time between literals that don't do variable
  1536.      substitution.  Backslash interpretation also happens at compile time.
  1537.      You can say
  1538.  
  1539.          'Now is the time for all' . "\n" .
  1540.              'good men to come to.'
  1541.  
  1542.      and this all reduces to one string internally.  Likewise, if you say
  1543.  
  1544.          foreach $file (@filenames) {
  1545.              if (-s $file > 5 + 100 * 2**16) { ... }
  1546.          }
  1547.  
  1548.      the compiler will precompute the number that expression represents so
  1549.      that the interpreter won't have to.
  1550.  
  1551.      IIIInnnntttteeeeggggeeeerrrr AAAArrrriiiitttthhhhmmmmeeeettttiiiicccc
  1552.  
  1553.      By default Perl assumes that it must do most of its arithmetic in
  1554.      floating point.  But by saying
  1555.  
  1556.          use integer;
  1557.  
  1558.      you may tell the compiler that it's okay to use integer operations from
  1559.      here to the end of the enclosing BLOCK.  An inner BLOCK may countermand
  1560.      this by saying
  1561.  
  1562.          no integer;
  1563.  
  1564.      which lasts until the end of that BLOCK.
  1565.  
  1566.      The bitwise operators ("&", "|", "^", "~", "<<", and ">>") always produce
  1567.      integral results.  However, use integer still has meaning for them.  By
  1568.      default, their results are interpreted as unsigned integers.  However, if
  1569.      use integer is in effect, their results are interpreted as signed
  1570.      integers.  For example, ~0 usually evaluates to a large integral value.
  1571.      However, use integer; ~0 is -1.
  1572.  
  1573.      FFFFllllooooaaaattttiiiinnnngggg----ppppooooiiiinnnntttt AAAArrrriiiitttthhhhmmmmeeeettttiiiicccc
  1574.  
  1575.      While use integer provides integer-only arithmetic, there is no similar
  1576.      ways to provide rounding or truncation at a certain number of decimal
  1577.      places.  For rounding to a certain number of digits, _s_p_r_i_n_t_f() or
  1578.  
  1579.  
  1580.  
  1581.                                                                        PPPPaaaaggggeeee 22224444
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1589.  
  1590.  
  1591.  
  1592.      _p_r_i_n_t_f() is usually the easiest route.
  1593.  
  1594.      The POSIX module (part of the standard perl distribution) implements
  1595.      _c_e_i_l(), _f_l_o_o_r(), and a number of other mathematical and trigonometric
  1596.      functions.  The Math::Complex module (part of the standard perl
  1597.      distribution) defines a number of mathematical functions that can also
  1598.      work on real numbers.  Math::Complex not as efficient as POSIX, but POSIX
  1599.      can't work with complex numbers.
  1600.  
  1601.      Rounding in financial applications can have serious implications, and the
  1602.      rounding method used should be specified precisely.  In these cases, it
  1603.      probably pays not to trust whichever system rounding is being used by
  1604.      Perl, but to instead implement the rounding function you need yourself.
  1605.  
  1606.  
  1607.  
  1608.  
  1609.  
  1610.  
  1611.  
  1612.  
  1613.  
  1614.  
  1615.  
  1616.  
  1617.  
  1618.  
  1619.  
  1620.  
  1621.  
  1622.  
  1623.  
  1624.  
  1625.  
  1626.  
  1627.  
  1628.  
  1629.  
  1630.  
  1631.  
  1632.  
  1633.  
  1634.  
  1635.  
  1636.  
  1637.  
  1638.  
  1639.  
  1640.  
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647.                                                                        PPPPaaaaggggeeee 22225555
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. PPPPEEEERRRRLLLLOOOOPPPP((((1111))))                                                            PPPPEEEERRRRLLLLOOOOPPPP((((1111))))
  1655.  
  1656.  
  1657.  
  1658.  
  1659.  
  1660.  
  1661.  
  1662.  
  1663.  
  1664.  
  1665.  
  1666.  
  1667.  
  1668.  
  1669.  
  1670.  
  1671.  
  1672.  
  1673.  
  1674.  
  1675.  
  1676.  
  1677.  
  1678.  
  1679.  
  1680.  
  1681.  
  1682.  
  1683.  
  1684.  
  1685.  
  1686.  
  1687.  
  1688.  
  1689.  
  1690.  
  1691.  
  1692.  
  1693.  
  1694.  
  1695.  
  1696.  
  1697.  
  1698.  
  1699.  
  1700.  
  1701.  
  1702.  
  1703.  
  1704.  
  1705.  
  1706.  
  1707.  
  1708.  
  1709.  
  1710.                                                                        PPPPaaaaggggeeee 22226666
  1711.  
  1712.  
  1713.  
  1714.  
  1715.  
  1716.  
  1717.